package DataAccess;

import android.content.Context;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by Administrator on 2017-09-02.
 */

public class DeviceDataAccess extends  DataAccess {


    /**
     * 创建或打开数据库
     *
     * @param context
     */
    public DeviceDataAccess(Context context) {
        super(context);
    }


    public JSONObject getById(String deviceId) {
        try {
            String sql = "select * from Device where id ='"+deviceId+"'";
            List<JSONObject> list = Select(sql);
            if (list != null && list.size() > 0) {
                JSONObject deviceInfo = list.get(0);
                JSONArray goodsArray = new JSONArray();
                if (!deviceInfo.getString("goodsList").equals("")) {
                    goodsArray = new JSONArray(deviceInfo.getString("goodsList"));
                }
                deviceInfo.put("goodsList",goodsArray);
                return deviceInfo;
            } else {
                return null;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public  boolean Delete(String deviceId)
    {
        String sql="delete from Device where id ='"+deviceId+"'";
        return ExecSql(sql);
    }

    public boolean setDevice(JSONObject deviceInfo) {
        try {
            String sql = "";
            JSONObject row = getById(deviceInfo.getString("id"));
            if (row == null) {
                if (deviceInfo.has("goodsList")){
                    sql = String.format("insert INTO Device(id,name,goodsList) values('%s','%s')",
                            deviceInfo.getString("id"), deviceInfo.getString("name"), deviceInfo.getString("goodsList"));
                } else {
                    sql = String.format("insert INTO Device(id,name,goodsList) values('%s','%s','')",
                            deviceInfo.getString("id"), deviceInfo.getString("name"));
                }
            } else {
                if (deviceInfo.has("goodsList")){
                    sql = String.format("update Device set `name` = '%s' , `goodsList` = '%s' where `id` = '%s'",
                            deviceInfo.getString("name"), deviceInfo.getString("goodsList"),deviceInfo.getString("id"));
                } else {
                    sql = String.format("update Device set `name` = '%s' , `goodsList` = '' where `id` = '%s'",
                            deviceInfo.getString("name"),deviceInfo.getString("id"));
                }
            }
            return ExecSql(sql);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

}
